const state ={
   // 空对象加引号啊啊啊啊啊啊啊啊 不然报错且没用
   carts:JSON.parse(uni.getStorageSync('carts')|| '[]') , 
    // 购物车的数组，用来存储购物车中每个商品的信息对象
       // { goods_id, goods_name, goods_price, goods_count, goods_small_logo, goods_state }
} 

const mutations ={
  // 获取购物车商品数据
  addToCart(state,goods){
   const  findResult = state.carts.find(x=> x.goods_id === goods.goods_id)
   if(!findResult){
     state.carts.push(goods)
   }else{
     findResult.goods_count++
   }
   this.commit('saveToStorage')
  },
  //存储到本地数据
  saveToStorage(state){
     uni.setStorageSync('carts',JSON.stringify(state.carts))
  },
  //购物车勾选状态的修改
  updateGoodsState(state,goods){
    //findResult 有的话就筛选出了对应id的对象
     const findResult = state.carts.find(x=> x.goods_id === goods.goods_id)
      if(findResult){
        if(goods.goods_state){
          //将该对象的状态修改
          findResult.goods_state = goods.goods_state
        }else if(goods.goods_count){
          findResult.goods_count = goods.goods_count
        }
      }
      //再次存储到本地数据
      this.commit('saveToStorage')
  },
  goodsDelete(state,goods){
     //过滤要删除的商品,并返回一个信数组
      state.carts = state.carts.filter(x=> x.goods_id !== goods.goods_id)
      //再次存储到本地数据
      this.commit('saveToStorage')
  },
  updateAllChecked(state,newState){
   newState=newState==1?2:1
    // if(newState){
    //   newState =2
    // }else{
    //   newState =1
    // }
    //改变所有商品的勾选状态
       state.carts.forEach((item)=> item.goods_state =newState )
       //再次存储到本地数据
       this.commit('saveToStorage')
  }
  
}

const actions={ 
  
}

const getters={
  //购物车中所有商品的总数量
   total(state){
     // let c = 0
     // state.carts.forEach(item=> c+= item.goods_count)
     // return c
     
    return state.carts.reduce((total,item)=>total += item.goods_count,0)
   },
   //购物车中已勾选的商品数量
   checkedCount(state){
     return state.carts.filter(x => x.goods_state==2).reduce((total,item)=> total += item.goods_count,0)
   },
   //已勾选商品的总价格
   checkedCountAmount(state){
    return state.carts.filter(x=> x.goods_state==2).reduce((total,item)=>total += item.goods_count*item.goods_price,0).toFixed(2)
   }
}

export default  {
  state,
  mutations,
  actions,
  getters
}